Option Strict Off
Option Explicit On
Imports VB = Microsoft.VisualBasic
Imports SDIFChecker
Imports System.IO
Imports System.Drawing.Printing

Friend Class frmMain
    Inherits System.Windows.Forms.Form

    Public MyDataGridViewPrinter As DataGridViewPrinter
    'Private HeaderText As String = "....+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8....+....9....+...10....+...11....+...12....+...13....+...14....+...15....+...16...."
    'Private SaveRowValue As String = ""

    Private Sub cmdCancel_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCancel.Click
        If cmdCancel.Text = "&Exit" Then
            Me.Close()
        ElseIf SDIFChecker.gbBreak = True Then
            ResetImportForm()
            SDIFChecker.gsSDIFName = ""
            cmdCheck.Enabled = False
            RegisteredFeatures(False)
            lblSDIFName.Text = "SDIF File: "
            lblComments.Text = ""
            cmdCancel.Text = "&Exit"
        ElseIf MsgBox("Cancel?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
            SDIFChecker.gbBreak = True
        End If
    End Sub

    Private Sub RegisteredFeatures(ByVal bFlag As Boolean)
        mnuFileCreate.Enabled = bFlag
        PrintPreviewToolStripMenuItem.Enabled = bFlag
        PrintToolStripMenuItem.Enabled = bFlag
        mnuFileExport.Enabled = bFlag
    End Sub

    Private Sub cmdCheck_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCheck.Click
        Dim tStr As String
        Dim style As Short
        Dim UseCount As Short
        Dim tbChk As Boolean

        cmdCancel.Text = "C&ancel"
        cmdCancel.Refresh()

        SDIFChecker.SetHourglass()
        tbChk = SDIFChecker.CheckSDIF(SDIFChecker.gsSDIFName, SDIFChecker.gsVersion)
        SDIFChecker.UnSetHourglass()

        UseCount = CShort(SDIFChecker.RegGetSetting(SDIFChecker.gsREGSDIFCHECK, SDIFChecker.gcSDIFCHECK, "UseCount", "0"))
        SDIFChecker.RegSaveSetting(SDIFChecker.gsREGSDIFCHECK, SDIFChecker.gcSDIFCHECK, "UseCount", CStr(UseCount + 1))

        If tbChk = True Then
            Exit Sub
        End If

        Select Case SDIFChecker.giError

            Case SDIFChecker.SDIF_WARNING
                style = MsgBoxStyle.Exclamation
                tStr = "Some WARNINGS occurred during analysis"

            Case SDIFChecker.SDIF_CRITICAL
                style = MsgBoxStyle.Critical
                tStr = "Some CRITICAL errors occurred during analysis"

            Case SDIFChecker.SDIF_INFORMATIONAL
                style = MsgBoxStyle.Information
                tStr = "Some INFORMATIONAL messages occurred during analysis"

            Case Else
                style = MsgBoxStyle.Information
                tStr = "No messages occurred during analysis"

        End Select

        cmdCancel.Text = "&Exit"
        cmdCancel.Refresh()
        ProgressBar1.Value = 0
        MsgBox(tStr, style)

    End Sub

    Private Sub frmMain_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            Dim s() As String = CType(e.Data.GetData(DataFormats.FileDrop), String())
            OpenSDIFFile(s(0))
        End If
    End Sub

    Private Sub frmMain_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
        Dim X As Short
        Dim tStr As String

        SDIFChecker.gsVersion = My.Application.Info.Version.Major & "." & My.Application.Info.Version.Minor & "." & My.Application.Info.Version.Revision
        cmdCheck.Enabled = False
        RegisteredFeatures(False)
        cmdCancel.Text = "&Exit"
        SDIFChecker.giFileNumber = -1

        ProgressBar1.Minimum = 0
        ProgressBar1.Value = 0

        SDIFChecker.gsVersion = Display_SDIF()
        For X = 1 To 4
            tStr = SDIFChecker.RegGetSetting(SDIFChecker.gsREGSDIFCHECK, SDIFChecker.gcSDIFCHECK, "SDIFFile" & X, "")
            If Len(tStr) > 0 Then
                Me.mnuFileDash1.Visible = True
                Me.mnuSDIF(X).Text = "&" & X & " " & tStr
                Me.mnuSDIF(X).Visible = True
            End If
        Next

        With DataGridView1.ColumnHeadersDefaultCellStyle
            .BackColor = Color.Navy
            .ForeColor = Color.White
            .Font = New Font(New System.Drawing.Font("Courier New", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)), FontStyle.Bold)
        End With

        Me.Show()
        ResetImportForm()

        Dim bWarnings As String = SDIFChecker.RegGetSetting(SDIFChecker.gsREGSDIFCHECK, SDIFChecker.gcSDIFCHECK, "SuppressWarnings", "False")
        mnuViewWarnings.Checked = IIf(bWarnings = "True", True, False)

    End Sub
    Private Function Display_SDIF() As String
        Dim tVersion As String

        tVersion = My.Application.Info.DirectoryPath & "\Templates\SDIF003.DDL"

        Display_SDIF = tVersion

        lblTemplate.Text = "SDIF Template: " & tVersion
        lblTemplate.Refresh()

        If File.Exists(tVersion) = False Then
            MsgBox("""" & tVersion & """  Not Found!", MsgBoxStyle.Critical)
            Me.Close()
        End If

    End Function

    Private Sub frmMain_FormClosed(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        Dim I As Short

        For I = 1 To 4
            'Debug.Print(String.Format("Name={0} Tag={1} Visible={2} ", Me.mnuSDIF(I).Text, Me.mnuSDIF(I).Tag, IIf(Me.mnuSDIF(I).Visible = True, "True", "False")))
            If Me.mnuSDIF(I).Text.Length > 2 Then
                SDIFChecker.RegSaveSetting(SDIFChecker.gsREGSDIFCHECK, SDIFChecker.gcSDIFCHECK, "SDIFFile" & I, Mid(Me.mnuSDIF(I).Text, 4, Len(Me.mnuSDIF(I).Text)))
                'SDIFChecker.RegSaveSetting(SDIFChecker.gsREGSDIFCHECK, SDIFChecker.gcSDIFCHECK, "SDIFConnect" & I, Me.mnuSDIF(I).Tag)
            Else
                SDIFChecker.RegSaveSetting(SDIFChecker.gsREGSDIFCHECK, SDIFChecker.gcSDIFCHECK, "SDIFFile" & I, "")
                'SDIFChecker.RegSaveSetting(SDIFChecker.gsREGSDIFCHECK, SDIFChecker.gcSDIFCHECK, "SDIFConnect" & I, "")
            End If
        Next

        SDIFChecker.RegSaveSetting(SDIFChecker.gsREGSDIFCHECK, SDIFChecker.gcSDIFCHECK, "SuppressWarnings", IIf(mnuViewWarnings.Checked = True, "True", "False"))

    End Sub

    Public Sub mnuFileCreate_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles mnuFileCreate.Click
        Dim tStr As String

        tStr = SDIFChecker.Create_Database(SDIFChecker.gsSDIFName)
        If Len(tStr) > 0 Then
            SDIFChecker.Load_Database(tStr)
            MsgBox(tStr & " created!", MsgBoxStyle.Information)
        End If

    End Sub

    Public Sub mnuFileExit_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles mnuFileExit.Click
        Me.Close()
    End Sub

    Public Sub mnuFileExport_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles mnuFileExport.Click

        Dim tStr As String = SDIFChecker.Create_SDF_File(SDIFChecker.gsSDIFName)
        If Len(tStr) > 0 Then
            MsgBox(tStr & " created!", MsgBoxStyle.Information)
        End If

    End Sub

    Public Sub mnuFileOpen_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles mnuFileOpen.Click

        Dim tStr As String

        ResetImportForm()

        Me.dlgCMD1Open.Filter = "SDIF Data (*.cl2;*.sdi;*.sd2;*.sd3;*.sd4)|*.cl2;*.sdi;*.sd2;*.sd3;*.sd4|Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
        Me.dlgCMD1Open.Title = "Open SDIF Data File"
        Me.dlgCMD1Open.FilterIndex = 1
        Me.dlgCMD1Open.FileName = ""
        Me.dlgCMD1Open.InitialDirectory = SDIFChecker.GetPath("")
        Me.dlgCMD1Open.ShowDialog()
        tStr = LTrim(Me.dlgCMD1Open.FileName)
        If Len(tStr) > 0 Then
            OpenSDIFFile(tStr)
        End If
    End Sub

    Private Sub OpenSDIFFile(ByVal tFile As String)
        SDIFChecker.SetPath(tFile)
        cmdCancel.Text = "C&ancel"
        If LoadSDIFImportGrid(tFile) = False Then
            SDIFChecker.gsSDIFName = tFile
            SDIFChecker.AddMRU(tFile)
            lblSDIFName.Text = "SDIF File: " & tFile
            cmdCheck.Enabled = True
            RegisteredFeatures(True)
            cmdCancel.Text = "&Exit"
            cmdCancel.Refresh()
        Else
            MsgBox("""A0"" not in first record!" & vbCrLf & "Processing cancelled, not a valid SDIF file!", MsgBoxStyle.Critical)
            ResetImportForm()
        End If
    End Sub

    Public Sub mnuSDIF_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles mnuSDIF.Click
        Dim Index As Short = mnuSDIF.GetIndex(eventSender)

        Dim tStr As String = Mid(mnuSDIF(Index).Text, 4, Len(mnuSDIF(Index).Text))

        If File.Exists(tStr) = True Then
            ResetImportForm()
            SDIFChecker.SetPath(tStr)
            cmdCancel.Text = "C&ancel"
            If LoadSDIFImportGrid(tStr) = False Then
                SDIFChecker.gsSDIFName = tStr
                SDIFChecker.AddMRU(tStr)
                lblSDIFName.Text = "SDIF File: " & tStr
                cmdCheck.Enabled = True
                RegisteredFeatures(True)
                cmdCancel.Text = "&Exit"
                cmdCancel.Refresh()
            Else
                MsgBox("""A0"" not in first record!" & vbCrLf & "Processing cancelled, not a valid SDIF file!", MsgBoxStyle.Critical)
                ResetImportForm()
            End If
        Else
            MsgBox(String.Format("{0} not found!", tStr))
        End If

    End Sub

    Public Sub mnuViewWarnings_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles mnuViewWarnings.Click
        If mnuViewWarnings.Checked = True Then
            mnuViewWarnings.Checked = False
        Else
            mnuViewWarnings.Checked = True
        End If
    End Sub

    Private Sub ResetImportForm()

        ProgressBar1.Value = 0
        RegisteredFeatures(False)
        SDIFChecker.SDIFErrorCount = 0

    End Sub

    Function LoadSDIFImportGrid(ByRef tFile As String) As Boolean
        Dim I As Short
        Dim varLine As String
        Dim FileNumber As Short
        Dim tStr As String

        SDIFChecker.SetHourglass()

        LoadSDIFImportGrid = True
        SDIFChecker.gbBreak = False

        ProgressBar1.Minimum = 0
        ProgressBar1.Value = 0
        ProgressBar1.Maximum = 1000

        I = 1

        DataGridView1.Rows.Clear()

        Try
            FileNumber = FreeFile()
            FileOpen(FileNumber, tFile, OpenMode.Input)
            Try
                Do While Not EOF(FileNumber)
                    If SDIFChecker.gbBreak = True Then
                        Exit Do
                    End If
                    varLine = LineInput(FileNumber)
                    If I = 1 Then
                        If VB.Left(varLine, 2) = "A0" Then
                            tStr = "File created by " & LTrim(Mid(varLine, 44, 20)) & ", Version "
                            tStr = tStr & LTrim(Mid(varLine, 64, 10)) & " on " & VB6.Format(CDate(VB6.Format(Mid(varLine, 106, 8), "##/##/####")), "mm/dd/yyyy") & vbCrLf
                            tStr = tStr & LTrim(Mid(varLine, 14, 30)) & vbCrLf
                            lblComments.Text = tStr
                            LoadSDIFImportGrid = False
                        Else
                            LoadSDIFImportGrid = True
                        End If
                        System.Windows.Forms.Application.DoEvents()
                    End If

                    If ProgressBar1.Value > 999 Then
                        ProgressBar1.Value = 0
                    Else
                        ProgressBar1.Value = ProgressBar1.Value + 1
                    End If

                    Dim row1 As String() = {VB6.Format(I, "###"), varLine}
                    DataGridView1.Rows.Add(row1)

                    I = I + 1

                Loop
            Catch ex As Exception
                MsgBox(String.Format("Loading error on {0} : Error : {1}", tFile, ex.Message), MsgBoxStyle.Critical)
            End Try

        Catch ex As Exception
            MsgBox(tFile & " not found!", MsgBoxStyle.Critical)
        Finally
            lblCount.Text = VB6.Format(I - 1, "####")
            ' Close before reopening in another mode.
            FileClose(FileNumber)
            SDIFChecker.giSDIFRecMax = I
        End Try
        ProgressBar1.Value = 0
        SDIFChecker.UnSetHourglass()
    End Function

    Private Sub PrintPreviewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintPreviewToolStripMenuItem.Click

        If SetupThePrinting() Then
            Dim MyPrintPreviewDialog As New PrintPreviewDialog()
            MyPrintPreviewDialog.Document = MyPrintDocument
            MyPrintPreviewDialog.ShowDialog()
        End If

    End Sub

    Private Sub PrintToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintToolStripMenuItem.Click

        If SetupThePrinting() Then
            MyPrintDocument.Print()
        End If

    End Sub

    Private Function SetupThePrinting() As Boolean

        Dim iMaxColumnWidth As Short

        Dim MyPrintDialog As New PrintDialog()
        MyPrintDialog.AllowCurrentPage = False
        MyPrintDialog.AllowPrintToFile = False
        MyPrintDialog.AllowSelection = False
        MyPrintDialog.AllowSomePages = False
        MyPrintDialog.PrintToFile = False
        MyPrintDialog.ShowHelp = False
        MyPrintDialog.ShowNetwork = False
        MyPrintDialog.PrinterSettings.DefaultPageSettings.Landscape = True

        If MyPrintDialog.ShowDialog() <> DialogResult.OK Then
            Return False
        End If

        MyPrintDocument.DocumentName = "SDIF Checker Report"
        MyPrintDocument.PrinterSettings = MyPrintDialog.PrinterSettings
        MyPrintDocument.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings
        MyPrintDocument.DefaultPageSettings.Margins = New Margins(40, 40, 40, 40)

        If MyPrintDocument.DefaultPageSettings.Landscape = True Then
            iMaxColumnWidth = 140
        Else
            iMaxColumnWidth = 105
        End If

        MyDataGridViewPrinter = New DataGridViewPrinter(DataGridView1, MyPrintDocument, False, True, "SDIF Checker : " & SDIFChecker.gsSDIFName, New Font("Tahoma", 12, FontStyle.Bold, GraphicsUnit.Point), _
        Color.Black, True, iMaxColumnWidth)

        Return True
    End Function

    Private Sub MyPrintDocument_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles MyPrintDocument.PrintPage
        Dim more As Boolean = MyDataGridViewPrinter.DrawDataGridView(e.Graphics)
        If more = True Then
            e.HasMorePages = True
        End If
    End Sub

    Private Sub DataGridView1_SortCompare( _
    ByVal sender As Object, ByVal e As DataGridViewSortCompareEventArgs) _
    Handles DataGridView1.SortCompare

        ' If the cells are equal, sort based on the ID column.
        If (e.Column.Name = "Count") Then
            e.SortResult = System.Decimal.Compare(Val(e.CellValue1.ToString()), Val(e.CellValue2.ToString()))
        ElseIf (e.Column.Name = "Record") Then
            e.SortResult = System.String.Compare(e.CellValue1.ToString.Substring(0, 2), _
                e.CellValue2.ToString.Substring(0, 2))
            'Debug.Print(String.Format("{0} {1}", e.CellValue1.ToString.Substring(1, 2), e.CellValue2.ToString.Substring(1, 2)))
            If (e.SortResult = 0) Then
                e.SortResult = System.Decimal.Compare( _
                    Val(DataGridView1.Rows(e.RowIndex1).Cells("Count").Value.ToString()), _
                    Val(DataGridView1.Rows(e.RowIndex2).Cells("Count").Value.ToString()))
            End If
        End If

        e.Handled = True

    End Sub
    
    Private Sub frmMain_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop, False) Then

            Dim strFile() As String = CType(e.Data.GetData(DataFormats.FileDrop), String())

            Dim fi As New System.IO.FileInfo(strFile(0))

            If fi.Extension.ToUpper = ".SD3" Or fi.Extension.ToUpper = ".CL2" Then

                e.Effect = DragDropEffects.Copy

            End If

        End If

    End Sub
    
End Class